/*
Copyright 2014 Yury Kharlamov

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated Inversion-Of-Control container
https://code.google.com/p/gen-ioc/

* * *

Worker class implementation for doing some lengthy job
*/
#include "stdafx.h"
#include "GenIOC/EventSourceBase.h"
#include "GenIOC/TaskQueue.h"
#include "StateMachine/state_machine.h"
#include "IWorker.h"
#include "IErrorReport.h"
#include "WorkerBase.h"


namespace WorkerStates
{
	enum Enum
	{
		Idle,
		Loading,
		ShutdownDone,
		ErrorOccurred
	};
};

using namespace state_machine;

class Worker : public WorkerBase, public ASM<WorkerStates::Enum>
{
		struct StartWork{};
		struct ShutDown{};
		struct WorkFinished{};
public:
	Worker()
		:ASM(WorkerStates::Idle)
		, m_isShutdownRequested(false)
	{
		State<WorkerStates::Enum> Idle(WorkerStates::Idle)
			, Loading(WorkerStates::Loading)
			, ShutdownDone(WorkerStates::ShutdownDone)
			, ErrorOccurred(WorkerStates::ErrorOccurred)
			, _ = State<WorkerStates::Enum>::Any();
		*this+=
			Idle + StartWork() > Loading - [=]{auto This = this; m_taskQueue.Queue([This]{This -> DoWork();}); },
			Loading + WorkFinished() > Idle - [=]{DispatchEvent(WorkResult()); },
			Idle / [=]{return m_isShutdownRequested; } > ShutdownDone - [=]{DispatchEvent(ShutdownFinished(this)); printf("Shutdown finished dispatched\n"); },
			_ + Error() > ErrorOccurred - [=](const Error e){ std::stringstream s; s << "Error in Worker: " << e.Text(); m_IErrorReport->ReportError(s.str()); },
			_ + ShutDown() > [=]{m_isShutdownRequested = true; printf("Shutdown requested\n"); }
		;
		SetOnAfterTransition([](WorkerStates::Enum from, WorkerStates::Enum to)
		{
			printf("Worker: %i->%i\n", from, to);
		});
	}
	void Download() override
	{
		QueueEvent(StartWork());
	}
	void Shutdown() override
	{
		QueueEvent(ShutDown());
	}
	~Worker()
	{
		m_taskQueue.Join();
	}
private:
	void DoWork()
	{
		static volatile LONG delay;
		InterlockedExchangeAdd(&delay, 10);
		Sleep(delay);
		QueueEvent(WorkFinished());
	}
	//boost::thread m_thread;
	TaskQueue m_taskQueue;
	bool m_isShutdownRequested;
};

std::shared_ptr<IObject> CreateWorker()
{
	return std::static_pointer_cast<IWorker>(std::make_shared<Worker>());
}